<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :expand-on-click-node="false" :data="depts" :props="defaultProps">
        <!-- 节点结构 -->
        <!-- v-slot="{ node, data }" 只能作用在template -->
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="operateDept($event,data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 通过组件传值id -->
    <AddDept
      ref="addDept"
      :show-dialog.sync="showDialog"
      :current-id="currentId"
      @update-depat="getDpartment"
    />
  </div>
</template>
<script>
import { getDpartment, delDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      currentId: null, // 接收ID
      showDialog: false,
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDpartment()
  },
  methods: {
    async  getDpartment() {
      const res = await getDpartment()
      // console.log(res)
      this.depts = transListToTreeData(res, 0)
    },
    operateDept(type, id) {
      // 根据类型进行判断
      if (type === 'add') {
        // 显示弹层
        this.showDialog = true
        // ID进行赋值
        this.currentId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentId = id
        this.$nextTick(() => {
          // 更新视图
          this.$refs.addDept.getDepartmentDetail()
          // this.$refs.addDept等同于子组件的this
        })
      } else {
        this.$confirm('确定要删除该数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDepartment(id)
          this.$message.success('删除角色成功')
          // 更新视图
          this.getDpartment()
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>

.tree-manager{
  margin: 10px;
  display:  inline-block;
  width: 50px;
}
</style>
